<template>
  <div class="prescriptions-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">处方查询</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/portal/patient' }">患者服务</el-breadcrumb-item>
          <el-breadcrumb-item>处方查询</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <el-card class="search-card">
        <div class="search-header">
          <h3 class="search-title">查询条件</h3>
        </div>
        
        <el-form :inline="true" :model="searchForm" ref="searchFormRef" class="search-form">
          <el-form-item label="开方时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              style="width: 320px"
            />
          </el-form-item>
          
          <el-form-item label="开方医生">
            <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" clearable style="width: 150px" />
          </el-form-item>
          
          <el-form-item label="开方科室">
            <el-select v-model="searchForm.department" placeholder="请选择科室" clearable style="width: 150px">
              <el-option label="全部科室" value="" />
              <el-option label="内科" value="内科" />
              <el-option label="外科" value="外科" />
              <el-option label="儿科" value="儿科" />
              <el-option label="妇产科" value="妇产科" />
              <el-option label="中医科" value="中医科" />
              <el-option label="皮肤科" value="皮肤科" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="处方状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="全部状态" value="" />
              <el-option label="待取药" value="pending" />
              <el-option label="已取药" value="dispensed" />
              <el-option label="已完成" value="completed" />
              <el-option label="已作废" value="cancelled" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><RefreshLeft /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <el-card class="prescriptions-card">
        <div class="prescriptions-header">
          <h3 class="prescriptions-title">处方列表</h3>
          <div class="prescriptions-stats">
            <span class="stat-item">共 {{ pagination.total }} 张处方</span>
            <span class="stat-item">待取药 {{ pendingCount }} 张</span>
          </div>
        </div>
        
        <el-table 
          :data="prescriptionsList" 
          v-loading="loading"
          style="width: 100%"
          stripe
          @row-click="handleRowClick"
        >
          <el-table-column prop="prescriptionDate" label="开方日期" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.prescriptionDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="prescriptionNo" label="处方号" width="160" />
          
          <el-table-column prop="doctorName" label="开方医生" width="120" />
          
          <el-table-column prop="department" label="开方科室" width="120" />
          
          <el-table-column prop="diagnosis" label="诊断" show-overflow-tooltip>
            <template #default="scope">
              <div v-if="scope.row.diagnosis && scope.row.diagnosis.length > 0">
                <el-tag v-for="(diag, index) in scope.row.diagnosis.slice(0, 2)" :key="index" size="small" class="diagnosis-tag">
                  {{ diag }}
                </el-tag>
                <span v-if="scope.row.diagnosis.length > 2" class="more-diagnosis">等{{ scope.row.diagnosis.length }}项</span>
              </div>
              <span v-else class="no-data">-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="drugCount" label="药品种类" width="100" align="center">
            <template #default="scope">
              {{ scope.row.medications ? scope.row.medications.length : 0 }}种
            </template>
          </el-table-column>
          
          <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
            <template #default="scope">
              <span class="amount-text">¥{{ scope.row.totalAmount ? scope.row.totalAmount.toFixed(2) : '0.00' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="290" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click.stop="handleViewDetail(scope.row)">
                  查看详情
                </el-button>
                <el-button size="small" type="info" @click.stop="handleViewGuidance(scope.row)">
                  用药指导
                </el-button>
                <el-button size="small" type="success" @click.stop="handleDownloadPrescription(scope.row)">
                  下载处方
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </div>
    
    <!-- 处方详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="处方详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentPrescription" class="prescription-detail">
        <div class="prescription-header">
          <h3>处方单</h3>
          <div class="prescription-meta">
            <span>处方号：{{ currentPrescription.prescriptionNo }}</span>
            <span class="divider">|</span>
            <span>开方日期：{{ formatDate(currentPrescription.prescriptionDate) }}</span>
          </div>
        </div>
        
        <el-descriptions :column="2" border class="prescription-info">
          <el-descriptions-item label="开方医生">
            {{ currentPrescription.doctorName }}
          </el-descriptions-item>
          <el-descriptions-item label="开方科室">
            {{ currentPrescription.department }}
          </el-descriptions-item>
          <el-descriptions-item label="处方类型">
            {{ getPrescriptionTypeText(currentPrescription.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="处方状态">
            <el-tag :type="getStatusType(currentPrescription.status)">
              {{ getStatusText(currentPrescription.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            <span class="amount-highlight">¥{{ currentPrescription.totalAmount ? currentPrescription.totalAmount.toFixed(2) : '0.00' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="取药时间" v-if="currentPrescription.dispensedTime">
            {{ formatDateTime(currentPrescription.dispensedTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>诊断信息</h4>
          <div class="content-box">
            <el-tag v-for="(diag, index) in (currentPrescription.diagnosis || [])" :key="index" class="diagnosis-tag">
              {{ diag }}
            </el-tag>
            <span v-if="!currentPrescription.diagnosis || currentPrescription.diagnosis.length === 0">无诊断信息</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>药品信息</h4>
          <div class="content-box">
            <el-table :data="currentPrescription.medications || []" size="small">
              <el-table-column prop="drugName" label="药品名称" />
              <el-table-column prop="specification" label="规格" width="120" />
              <el-table-column prop="quantity" label="数量" width="80" align="center" />
              <el-table-column prop="unit" label="单位" width="60" />
              <el-table-column prop="dosage" label="用法用量" show-overflow-tooltip />
              <el-table-column prop="unitPrice" label="单价" width="80" align="right">
                <template #default="scope">
                  ¥{{ scope.row.unitPrice ? scope.row.unitPrice.toFixed(2) : '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="subtotal" label="小计" width="80" align="right">
                <template #default="scope">
                  ¥{{ scope.row.subtotal ? scope.row.subtotal.toFixed(2) : '0.00' }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>医嘱</h4>
          <div class="content-box">
            {{ currentPrescription.instructions || '无特殊医嘱' }}
          </div>
        </div>
        
        <div class="detail-section">
          <h4>备注</h4>
          <div class="content-box">
            {{ currentPrescription.remarks || '无' }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="info" @click="handleViewGuidanceInDetail">用药指导</el-button>
        <el-button type="primary" @click="handleDownloadCurrent">下载处方</el-button>
      </template>
    </el-dialog>
    
    <!-- 用药指导弹窗 -->
    <el-dialog
      v-model="guidanceDialogVisible"
      title="用药指导"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="guidancePrescription" class="guidance-content">
        <div class="guidance-header">
          <h3>{{ guidancePrescription.prescriptionNo }} - 用药指导</h3>
        </div>
        
        <div v-for="(medication, index) in (guidancePrescription.medications || [])" :key="index" class="medication-guidance">
          <el-card class="medication-card" shadow="hover">
            <template #header>
              <div class="medication-title">
                <h4>{{ medication.drugName }}</h4>
                <el-tag size="small">{{ medication.specification }}</el-tag>
              </div>
            </template>
            
            <div class="guidance-item">
              <label>用法用量：</label>
              <span>{{ medication.dosage }}</span>
            </div>
            
            <div class="guidance-item">
              <label>服用时间：</label>
              <span>{{ medication.takingTime || '请遵医嘱' }}</span>
            </div>
            
            <div class="guidance-item">
              <label>注意事项：</label>
              <div class="notice-content">
                <p v-for="(notice, idx) in (medication.notices || getDefaultNotices(medication.drugName))" :key="idx">
                  {{ notice }}
                </p>
              </div>
            </div>
            
            <div class="guidance-item">
              <label>不良反应：</label>
              <span>{{ medication.sideEffects || '如有不适请及时就医' }}</span>
            </div>
            
            <div class="guidance-item">
              <label>禁忌：</label>
              <span>{{ medication.contraindications || '请仔细阅读药品说明书' }}</span>
            </div>
          </el-card>
        </div>
        
        <div class="general-guidance">
          <el-alert
            title="用药提醒"
            type="warning"
            :closable="false"
            show-icon
          >
            <p>1. 请严格按照医生开具的用法用量服药，不要自行增减剂量</p>
            <p>2. 如在用药过程中出现不良反应，请立即停药并咨询医生</p>
            <p>3. 请在有效期内使用药品，过期药品请及时处理</p>
            <p>4. 请将药品放在儿童不易接触的地方</p>
            <p>5. 如有疑问，请及时咨询医生或药师</p>
          </el-alert>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="guidanceDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrintGuidance">打印指导</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { patientAPI } from '@/utils/api'
import { format } from 'date-fns'
import { Search, RefreshLeft, Document, Download, View, Printer } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const prescriptionsList = ref([])
const detailDialogVisible = ref(false)
const guidanceDialogVisible = ref(false)
const currentPrescription = ref(null)
const guidancePrescription = ref(null)
const currentPatient = ref(null)

// 搜索表单
const searchForm = reactive({
  doctorName: '',
  department: '',
  status: ''
})

const dateRange = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 待取药数量
const pendingCount = computed(() => {
  return prescriptionsList.value.filter(prescription => prescription.status === 'pending').length
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'dispensed': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待取药',
    'dispensed': '已取药',
    'completed': '已完成',
    'cancelled': '已作废'
  }
  return texts[status] || '未知'
}

// 获取处方类型文本
const getPrescriptionTypeText = (type) => {
  const texts = {
    'western': '西药处方',
    'chinese': '中药处方',
    'mixed': '中西药处方'
  }
  return texts[type] || '普通处方'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd')
  } catch {
    return date
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
  } catch {
    return date
  }
}

// 获取默认用药注意事项
const getDefaultNotices = (drugName) => {
  // 这里可以根据药品名称返回对应的注意事项
  const defaultNotices = [
    '请按时服药，不要随意停药',
    '如有不良反应请及时就医',
    '请仔细阅读药品说明书'
  ]
  
  // 可以根据药品名称添加特定的注意事项
  if (drugName.includes('阿莫西林')) {
    return [...defaultNotices, '青霉素过敏者禁用', '饭后服用减少胃肠道刺激']
  }
  
  if (drugName.includes('布洛芬')) {
    return [...defaultNotices, '有胃溃疡病史者慎用', '不宜长期大量使用']
  }
  
  return defaultNotices
}

// 获取当前患者信息
const getCurrentPatient = async () => {
  try {
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?._id
    console.log('当前用户ID:', currentUserId)
    
    if (!currentUserId) {
      throw new Error('未找到当前用户ID')
    }
    
    // 通过用户ID获取患者信息
    const res = await patientAPI.getPatients({ userId: currentUserId })
    console.log('患者查询响应:', res)
    
    if (res.success && res.data && res.data.patients && res.data.patients.length > 0) {
      currentPatient.value = res.data.patients[0]
      console.log('找到当前患者:', currentPatient.value)
      return currentPatient.value
    } else {
      throw new Error('未找到对应的患者信息')
    }
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败，请联系管理员')
    throw error
  }
}

// 加载处方数据
const loadPrescriptions = async () => {
  try {
    loading.value = true
    
    // 如果还没有患者信息，先获取
    if (!currentPatient.value) {
      await getCurrentPatient()
    }
    
    // 确保有患者信息
    if (!currentPatient.value) {
      ElMessage.error('未找到患者信息，无法加载处方记录')
      return
    }
    
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      patientId: currentPatient.value?.id || currentPatient.value?._id
    }
    
    console.log('查询处方参数:', params)
    
    // 添加搜索条件
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    if (searchForm.doctorName) {
      params.doctorName = searchForm.doctorName
    }
    
    if (searchForm.department) {
      params.department = searchForm.department
    }
    
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    // 如果URL中有recordId参数，则筛选相关处方
    if (route.query.recordId) {
      params.medicalRecordId = route.query.recordId
    }
    
    const res = await patientAPI.getPrescriptions(params)
    
    if (res.success && res.data) {
      prescriptionsList.value = res.data.prescriptions || res.data.items || []
      pagination.total = res.data.total || 0
    } else {
      // 如果API请求失败，使用模拟数据
      loadMockData()
    }
  } catch (error) {
    console.error('加载处方数据失败:', error)
    // 加载模拟数据
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  const mockPrescriptions = [
    {
      id: '1',
      prescriptionNo: 'RX2024011501',
      prescriptionDate: '2024-01-15',
      doctorName: '张医生',
      department: '内科',
      type: 'western',
      diagnosis: ['感冒', '发热'],
      totalAmount: 85.50,
      status: 'completed',
      dispensedTime: '2024-01-15 14:30:00',
      instructions: '按时服药，多休息，多饮水',
      remarks: '如症状无缓解请复诊',
      medications: [
        {
          drugName: '阿莫西林胶囊',
          specification: '0.25g×12粒',
          quantity: 2,
          unit: '盒',
          dosage: '每次2粒，每日3次，饭后服用',
          unitPrice: 15.50,
          subtotal: 31.00,
          takingTime: '饭后30分钟',
          notices: ['青霉素过敏者禁用', '饭后服用减少胃肠道刺激', '完成整个疗程'],
          sideEffects: '可能出现腹泻、恶心等胃肠道反应',
          contraindications: '青霉素过敏者禁用'
        },
        {
          drugName: '感冒颗粒',
          specification: '10g×9袋',
          quantity: 1,
          unit: '盒',
          dosage: '每次1袋，每日3次，温水冲服',
          unitPrice: 25.50,
          subtotal: 25.50,
          takingTime: '饭前或饭后均可',
          notices: ['用温水冲服', '避免与其他感冒药同时使用'],
          sideEffects: '偶见皮疹、头晕',
          contraindications: '孕妇慎用'
        },
        {
          drugName: '布洛芬缓释胶囊',
          specification: '0.3g×10粒',
          quantity: 1,
          unit: '盒',
          dosage: '每次1粒，每日2次，发热时服用',
          unitPrice: 29.00,
          subtotal: 29.00,
          takingTime: '饭后服用',
          notices: ['仅在发热时服用', '不宜长期使用', '有胃病史者慎用'],
          sideEffects: '可能出现胃痛、头晕、皮疹',
          contraindications: '有胃溃疡、肾功能不全者禁用'
        }
      ]
    },
    {
      id: '2',
      prescriptionNo: 'RX2024011202',
      prescriptionDate: '2024-01-12',
      doctorName: '李医生',
      department: '外科',
      type: 'western',
      diagnosis: ['胃炎'],
      totalAmount: 68.00,
      status: 'dispensed',
      dispensedTime: '2024-01-12 16:20:00',
      instructions: '规律饮食，避免辛辣刺激食物',
      remarks: '2周后复查',
      medications: [
        {
          drugName: '奥美拉唑肠溶胶囊',
          specification: '20mg×14粒',
          quantity: 1,
          unit: '盒',
          dosage: '每次1粒，每日1次，晨起空腹服用',
          unitPrice: 38.00,
          subtotal: 38.00,
          takingTime: '晨起空腹',
          notices: ['空腹服用效果更佳', '整粒吞服，不要咀嚼'],
          sideEffects: '偶见头痛、腹泻、恶心',
          contraindications: '对本品过敏者禁用'
        },
        {
          drugName: '多潘立酮片',
          specification: '10mg×30片',
          quantity: 1,
          unit: '盒',
          dosage: '每次1片，每日3次，饭前服用',
          unitPrice: 30.00,
          subtotal: 30.00,
          takingTime: '饭前15-30分钟',
          notices: ['饭前服用', '避免与抗酸药同时服用'],
          sideEffects: '偶见口干、腹泻',
          contraindications: '胃肠道出血、穿孔者禁用'
        }
      ]
    },
    {
      id: '3',
      prescriptionNo: 'RX2024011003',
      prescriptionDate: '2024-01-10',
      doctorName: '王医生',
      department: '中医科',
      type: 'chinese',
      diagnosis: ['脾胃虚弱'],
      totalAmount: 156.00,
      status: 'pending',
      instructions: '煎煮方法：加水800ml，煎煮30分钟，取汁300ml，分2次服用',
      remarks: '服药期间忌食生冷',
      medications: [
        {
          drugName: '党参',
          specification: '优质',
          quantity: 30,
          unit: 'g',
          dosage: '煎煮服用',
          unitPrice: 2.50,
          subtotal: 75.00
        },
        {
          drugName: '白术',
          specification: '优质',
          quantity: 15,
          unit: 'g',
          dosage: '煎煮服用',
          unitPrice: 3.00,
          subtotal: 45.00
        },
        {
          drugName: '茯苓',
          specification: '优质',
          quantity: 12,
          unit: 'g',
          dosage: '煎煮服用',
          unitPrice: 3.00,
          subtotal: 36.00
        }
      ]
    }
  ]
  
  prescriptionsList.value = mockPrescriptions
  pagination.total = mockPrescriptions.length
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadPrescriptions()
}

// 重置搜索
const handleReset = () => {
  searchForm.doctorName = ''
  searchForm.department = ''
  searchForm.status = ''
  dateRange.value = []
  pagination.currentPage = 1
  loadPrescriptions()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadPrescriptions()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadPrescriptions()
}

// 行点击处理
const handleRowClick = (row) => {
  handleViewDetail(row)
}

// 查看详情
const handleViewDetail = (row) => {
  currentPrescription.value = row
  detailDialogVisible.value = true
}

// 查看用药指导
const handleViewGuidance = (row) => {
  guidancePrescription.value = row
  guidanceDialogVisible.value = true
}

// 详情中查看用药指导
const handleViewGuidanceInDetail = () => {
  if (currentPrescription.value) {
    detailDialogVisible.value = false
    handleViewGuidance(currentPrescription.value)
  }
}

// 下载处方
const handleDownloadPrescription = (row) => {
  ElMessage.success('处方下载中...')
  downloadPrescription(row.prescriptionNo)
}

// 下载当前处方
const handleDownloadCurrent = () => {
  if (currentPrescription.value) {
    handleDownloadPrescription(currentPrescription.value)
  }
}

// 下载处方文件
const downloadPrescription = async (prescriptionNo) => {
  try {
    // 模拟下载
    const link = document.createElement('a')
    link.href = `data:text/plain;charset=utf-8,处方号: ${prescriptionNo}`
    link.download = `处方_${prescriptionNo}.pdf`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 打印用药指导
const handlePrintGuidance = () => {
  window.print()
}

// 检查用户是否已登录并初始化数据
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再查看处方记录')
    router.push({
      path: '/portal/login',
      query: { redirect: '/portal/patient/prescriptions' }
    })
    return
  }
  
  // 已登录，先获取患者信息，再加载处方数据
  try {
    await getCurrentPatient()
    await loadPrescriptions()
    
    // 如果URL中有prescriptionId参数，则直接显示该处方的详情
    if (route.query.prescriptionId) {
      const prescriptionId = route.query.prescriptionId
      const prescription = prescriptionsList.value.find(p => p.id === prescriptionId)
      if (prescription) {
        handleViewDetail(prescription)
      } else {
        ElMessage.warning('未找到指定的处方记录')
      }
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    // 即使获取患者信息失败，也尝试加载模拟数据
    loadMockData()
    
    // 如果有prescriptionId参数，尝试在模拟数据中查找
    if (route.query.prescriptionId) {
      const prescriptionId = route.query.prescriptionId
      const prescription = prescriptionsList.value.find(p => p.id === prescriptionId)
      if (prescription) {
        handleViewDetail(prescription)
      }
    }
  }
})
</script>

<style scoped>
.prescriptions-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-card, .prescriptions-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-header, .prescriptions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-title, .prescriptions-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.prescriptions-stats {
  color: #666;
  font-size: 14px;
}

.stat-item {
  margin-left: 15px;
}

.search-form {
  margin-top: 20px;
}

.diagnosis-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.more-diagnosis {
  color: #666;
  font-size: 12px;
}

.no-data {
  color: #999;
}

.amount-text {
  color: #E6A23C;
  font-weight: 600;
}

.amount-highlight {
  color: #F56C6C;
  font-size: 18px;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.prescription-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.prescription-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e9ecef;
}

.prescription-header h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 20px;
}

.prescription-meta {
  color: #666;
  font-size: 14px;
}

.divider {
  margin: 0 10px;
}

.prescription-info {
  margin-bottom: 20px;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.content-box {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
  min-height: 40px;
  line-height: 1.5;
}

.guidance-content {
  max-height: 70vh;
  overflow-y: auto;
}

.guidance-header {
  text-align: center;
  margin-bottom: 20px;
}

.guidance-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.medication-guidance {
  margin-bottom: 20px;
}

.medication-card {
  border-left: 4px solid #409EFF;
}

.medication-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.medication-title h4 {
  margin: 0;
  color: #333;
}

.guidance-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.guidance-item label {
  min-width: 80px;
  font-weight: 600;
  color: #333;
  margin-right: 10px;
}

.notice-content p {
  margin: 5px 0;
  color: #666;
  line-height: 1.5;
}

.general-guidance {
  margin-top: 20px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

.general-guidance p {
  margin: 8px 0;
  color: #333;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.action-buttons .el-button {
  margin: 0;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .prescriptions-stats {
    margin-top: 10px;
  }
  
  .stat-item {
    display: block;
    margin-left: 0;
    margin-bottom: 5px;
  }
  
  .guidance-item {
    flex-direction: column;
  }
  
  .guidance-item label {
    min-width: auto;
    margin-bottom: 5px;
  }
}
</style> 